package router

import (
	"github.com/gin-gonic/gin"
	"log"
	"short-video-media/client/client"
	"short-video-media/client/request"
	work "short-video-media/common/proto"
)

func AddWork(c *gin.Context) {
	var data request.AddWork
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "请求失败！无法找到请求的资源！",
			"data": err.Error(),
		})
		return
	}
	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)

	dst := "./img/" + file.Filename
	// 上传文件至指定的完整文件路径
	err = c.SaveUploadedFile(file, "./img/"+file.Filename)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "请求失败！无法找到请求的资源！",
			"data": err.Error(),
		})
		return
	}
	addWork, err := client.AddWork(c, &work.AddWorkReq{
		UserId:       data.UserId,
		WorksName:    data.WorksName,
		WorksContent: data.WorksContent,
		WorksType:    data.WorksType,
		WorksUrl:     dst,
		TimeCount:    data.TimeCount,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"msg":  "请求失败！服务器内部错误",
			"data": err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "服务器响应正常",
		"data": addWork,
	})

}

func UpdateWork(c *gin.Context) {
	var data request.UpdateWork
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "请求失败！无法找到请求的资源！",
			"data": err.Error(),
		})
		return
	}
	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)

	dst := "./img/" + file.Filename
	// 上传文件至指定的完整文件路径
	err = c.SaveUploadedFile(file, "./img/"+file.Filename)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "请求失败！无法找到请求的资源！",
			"data": err.Error(),
		})
		return
	}
	upWork, err := client.UpdateWork(c, &work.UpdateWorkReq{
		WorksName:    data.WorksName,
		WorksContent: data.WorksContent,
		WorksType:    data.WorksType,
		WorksUrl:     dst,
		TimeCount:    data.TimeCount,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"msg":  "请求失败！服务器内部错误",
			"data": err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "服务器响应正常",
		"data": upWork,
	})
}

func FindWork(c *gin.Context) {
	var data request.FindWork
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1000,
			"msg":  "请求失败！无法找到请求的资源！",
			"data": err.Error(),
		})
		return
	}

	addWork, err := client.FindWork(c, &work.FindWorkReq{
		KeyWord: data.KeyWord,
	})
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1001,
			"msg":  "请求失败！服务器内部错误",
			"data": err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 0,
		"msg":  "服务器响应正常",
		"data": addWork,
	})
}
